package com.chinameyer.workorders.controller;

import com.alibaba.excel.EasyExcel;
import com.chinameyer.workorders.bean.MeyerWorkOrders;
import com.chinameyer.workorders.dto.orders.*;
import com.chinameyer.workorders.service.WorkOrderService;
import com.chinameyer.workorders.utils.ExcelReadUtil;
import com.chinameyer.workorders.vo.WorkOrders4AdminVO;
import com.chinameyer.workorders.vo.WorkOrders4StaffVO;
import com.xinmachong.response.ApiResponse;
import com.xinmachong.response.ApiResponseWithPage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author meyer@HongYe
 */
@RestController
@RequestMapping("/v1/workorders")
@Validated
@CrossOrigin
public class WorkOrderController {

    @Resource
    private WorkOrderService workOrderService;
    @Value("${mydefine.address}")
    private String address;
    @Value("${mydefine.out-port}")
    private String port;


    @PutMapping("/uploadExcel")
    public ApiResponse uploadExcel(@RequestParam("file") MultipartFile file,
                                   @RequestParam("catalogueId") int catalogueId) throws IOException {
        boolean isThirdLevel = this.workOrderService.checkThirdLevel(catalogueId);
        if (!isThirdLevel) {
            return new ApiResponse(400,"当前目录下无法导入EXCEL",0);
        }
        EasyExcel.read(file.getInputStream(), MeyerWorkOrders.class,new ExcelReadUtil(workOrderService,catalogueId)).sheet().doRead();
        return new ApiResponse(200,"success",1);
    }


    @GetMapping("/getDownloadUrl")
    public ApiResponse getDownloadUrl(@RequestParam(name = "startTime")String startTime,
                                      @RequestParam(name = "endTime")String endTime) {
        return new ApiResponse(200,"success",address + ":" + port + "/v1/workorders/downloadExcel?startTime="+startTime+"&endTime="+endTime);
    }


    @GetMapping("/downloadExcel")
    public ApiResponse downloadExcel(HttpServletResponse response,
                                     @RequestParam(name = "startTime")String startTime,
                                     @RequestParam(name = "endTime")String endTime) {
        List<WorkOrders4AdminVO> workOrders4AdminVOList = this.workOrderService.getAllWorkOrdersWithoutPaging(startTime,endTime);
        String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
        try {
            String fileName = new String((date+".xlsx").getBytes(), "ISO-8859-1");
            response.addHeader("Content-Disposition", "filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            EasyExcel.write(out, WorkOrders4AdminVO.class).sheet("工时单").doWrite(workOrders4AdminVOList);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ApiResponse(200,"success",1);
    }


    @PostMapping("/add")
    public ApiResponse add(@RequestBody @Validated AddWorkOrdersDTO addWorkOrdersDTO) {
        try {
            this.workOrderService.addOrders(addWorkOrdersDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"添加工单失败，请稍后重新添加或联系系统管理员",0);
        }
    }


    @DeleteMapping("/delete")
    public ApiResponse delete(@RequestParam(value = "orderId") Integer orderId) {
        try {
            this.workOrderService.deleteWorkOrders(orderId);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"删除工单失败，请稍后重新删除或联系系统管理员",0);
        }
    }


    @PostMapping("/edit")
    public ApiResponse edit(@RequestBody @Validated UpdateWorkOrdersDTO updateWorkOrdersDTO) {
        try {
            this.workOrderService.editOrders(updateWorkOrdersDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"编辑工单失败，请稍后重新编辑或联系系统管理员",0);
        }
    }


    @GetMapping("/getAll4Admin")
    public ApiResponseWithPage getAll4Admin(@RequestParam(name = "productNo",required = false,defaultValue = "")String productNo,
                                            @RequestParam(name = "productName",required = false,defaultValue = "")String productName,
                                            @RequestParam(name = "catalogueId")int catalogueId,
                                            @RequestParam(name = "count", required = false, defaultValue = "10")
                                            @Min(value = 1, message = "分页数量必须为正整数") Integer count,
                                            @RequestParam(name = "page", required = false, defaultValue = "1")
                                            @Min(value = 0, message = "分页必须为正整数") Integer page) {
        List<WorkOrders4AdminVO> workOrders4AdminVOList = this.workOrderService.getAllWorkOrders(productNo,productName,catalogueId,count,page - 1);
        int total = this.workOrderService.getAllWorkOrdersTotal(productNo,productName,catalogueId);
        return new ApiResponseWithPage(200,"success", workOrders4AdminVOList,total);
    }


    /**
     * 前端页面--添加工时与个人信息
     * @param addStaffAndTimeDTO 工时与个人信息
     * @return 添加结果响应
     */
    @PostMapping("/addStaffAndTime")
    public ApiResponse addStaffAndTime (@RequestBody @Validated AddStaffAndTimeDTO addStaffAndTimeDTO) {
        boolean isOversize = this.workOrderService.checkStaffAndTimeSize(addStaffAndTimeDTO);
        if (isOversize) {
            return new ApiResponse(400,"该任务填写人数已经超过十个，无法再添加",0);
        }
        try {
            int id = this.workOrderService.addStaffAndTime(addStaffAndTimeDTO);
            return new ApiResponse(200,"success",id);
        } catch (Exception e) {
            return new ApiResponse(400,"添加工时单失败，请稍后重新添加或联系系统管理员",0);
        }
    }


    /**
     * 前端页面--删除工时与个人信息
     * @param staffAndTimeId 工时信息ID
     * @return 删除结果响应
     */
    @DeleteMapping("/deleteStaffAndTime")
    public ApiResponse deleteStaffAndTime(@RequestParam(value = "staffAndTimeId") Integer staffAndTimeId) {
        try {
            this.workOrderService.deleteStaffAndTime(staffAndTimeId);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"删除工单失败，请稍后重新删除或联系系统管理员",0);
        }
    }


    @PostMapping("/editStaffAndTime")
    public ApiResponse editStaffAndTime(@RequestBody @Validated EditStaffAndTimeDTO editStaffAndTimeDTO) {
        try {
            this.workOrderService.editStaffAndTime(editStaffAndTimeDTO);
            return new ApiResponse(200,"success",1);
        } catch (Exception e) {
            return new ApiResponse(400,"编辑工时单失败，请稍后重新编辑或联系系统管理员",0);
        }
    }


    @GetMapping("/getAll4Staff")
    public ApiResponseWithPage getAll4Staff(@RequestParam(name = "productNo",required = false,defaultValue = "")String productNo,
                                            @RequestParam(name = "productName",required = false,defaultValue = "")String productName,
                                            @RequestParam(name = "catalogueId")int catalogueId,
                                            @RequestParam(name = "count", required = false, defaultValue = "10")
                                            @Min(value = 1, message = "分页数量必须为正整数") Integer count,
                                            @RequestParam(name = "page", required = false, defaultValue = "1")
                                            @Min(value = 0, message = "分页必须为正整数") Integer page) {
        List<WorkOrders4StaffVO> workOrders4StaffVOList = this.workOrderService.getAll4Staff(productNo,productName,catalogueId,count,page - 1);
        int total = this.workOrderService.getAllActiveWorkOrdersTotal(productNo,productName,catalogueId);
        return new ApiResponseWithPage(200,"success", workOrders4StaffVOList,total);
    }
}
